<?php

class MySqlHelper {
	
	private static $_instance;
	
	private $link;
	
	private $query;
	
	private $result;
	
	private $dbHostName;
	
	private $dbUsername;
	
	private $dbPassword;
	
	private $dbName;
	
	public static function getInstance() {
		if (self::$_instance == null) {
			self::$_instance = new MySqlHelper;
			
			self::$_instance->getConfig();
			self::$_instance->connect();
			self::$_instance->selectDB();
		}
	
		return self::$_instance;
	}
	
	private function getConfig() {
		$db_config = new Properties(CONFIG . '/database.xml');
		
		$this->dbHostName = $db_config->get('DB_HOSTNAME');
		$this->dbUsername = $db_config->get('DB_USERNAME');
		$this->dbPassword = $db_config->get('DB_PASSWORD');
		$this->dbName = $db_config->get('DB_NAME');
	}
	
	private function connect() {
		 $this->link = mysql_connect($this->dbHostName, $this->dbUsername, $this->dbPassword);
	}
	
	private function selectDB() {
		mysql_select_db($this->dbName, $this->link);
	}
	
	public function execute() {
		$this->result = mysql_query($this->query);
		
		echo mysql_error();
	}
	
	public function getAffectedRows(){
		return mysql_affected_rows($this->link);
	}
	
	public function getResult() {
		return $this->result;
	}
	
	public function getResultAssoc() {
		return mysql_fetch_assoc($this->result);
	}
	
	public function getLastId() {
		return mysql_insert_id($this->link);
	}
	
	public function query($query) {
		$this->query = $query;
	}
	
	public function insert($table, $data) {
		$values = array_map('mysql_real_escape_string', array_values($data));
		$keys = array_keys($data);
		 
		$this->query = 'INSERT INTO `' . $table . '` (`' . implode('`,`', $keys) . '`) VALUES (\'' . implode('\',\'', $values) . '\')';
	}
	
	public function delete($table, $where) {
		$condition = array();
		
		foreach ($where AS $k => $v) {
			$condition[] = $k . ' = \'' . $v . '\'';
		}
		
		$this->query = 'DELETE FROM `' . $table . '` WHERE ' . implode(' AND ', $condition);
	}
	
	public function update($table, $data, $where) {
		$condition = array();
		$datas = array();
		
		foreach ($where AS $k => $v) {
			$condition[] = $k . ' = \'' . $v . '\'';
		}
		
		foreach ($data AS $k => $v) {
			$datas[] = $k . ' = \'' . $v . '\'';
		}
		
		$this->query = 'UPDATE `' . $table . '` SET ' . implode(',', $datas) . ' WHERE ' . implode(' AND ', $condition);
	}
	
}